<template>
  <div class="config-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form
        ref="queryFormRef"
        :model="queryForm"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="参数名称" prop="configName">
          <el-input
            v-model="queryForm.configName"
            placeholder="请输入参数名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="参数键名" prop="configKey">
          <el-input
            v-model="queryForm.configKey"
            placeholder="请输入参数键名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="系统内置" prop="configType">
          <el-select
            v-model="queryForm.configType"
            placeholder="系统内置"
            clearable
            style="width: 200px"
          >
            <el-option label="是" value="Y" />
            <el-option label="否" value="N" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" style="width: 308px">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="Refresh" @click="resetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-bar">
        <div class="left-operations">
          <el-button
            v-permission="['system:config:add']"
            type="primary"
            icon="Plus"
            @click="handleAdd"
          >
            新增
          </el-button>
          <el-button
            v-permission="['system:config:edit']"
            type="success"
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
          >
            修改
          </el-button>
          <el-button
            v-permission="['system:config:remove']"
            type="danger"
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
          >
            删除
          </el-button>
          <el-button
            v-permission="['system:config:export']"
            type="warning"
            icon="Download"
            @click="handleExport"
          >
            导出
          </el-button>
          <el-button
            v-permission="['system:config:remove']"
            type="danger"
            icon="Refresh"
            @click="handleRefreshCache"
          >
            刷新缓存
          </el-button>
        </div>
        <div class="right-operations">
          <el-tooltip content="刷新" placement="top">
            <el-button icon="Refresh" circle @click="getList" />
          </el-tooltip>
        </div>
      </div>

      <!-- 参数配置列表 -->
      <el-table
        v-loading="loading"
        :data="configList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="参数主键" prop="configId" width="100" />
        <el-table-column
          label="参数名称"
          prop="configName"
          show-overflow-tooltip
        />
        <el-table-column
          label="参数键名"
          prop="configKey"
          show-overflow-tooltip
        />
        <el-table-column
          label="参数键值"
          prop="configValue"
          show-overflow-tooltip
        />
        <el-table-column label="系统内置" prop="configType" width="100">
          <template #default="{ row }">
            <dict-tag :options="yesNoOptions" :value="row.configType" />
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" show-overflow-tooltip />
        <el-table-column
          label="创建时间"
          prop="createTime"
          width="160"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>{{ parseTime(row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="180"
          class-name="small-padding fixed-width"
        >
          <template #default="{ row }">
            <el-tooltip content="修改" placement="top">
              <el-button
                v-permission="['system:config:edit']"
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(row)"
              />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                v-permission="['system:config:remove']"
                link
                type="danger"
                icon="Delete"
                @click="handleDelete(row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" :before-close="cancel">
      <el-form ref="configFormRef" :model="configForm" :rules="configFormRules" label-width="80px">
        <el-form-item label="参数名称" prop="configName">
          <el-input v-model="configForm.configName" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="参数键名" prop="configKey">
          <el-input v-model="configForm.configKey" placeholder="请输入参数键名" />
        </el-form-item>
        <el-form-item label="参数键值" prop="configValue">
          <el-input v-model="configForm.configValue" type="textarea" placeholder="请输入参数键值" />
        </el-form-item>
        <el-form-item label="系统内置" prop="configType">
          <el-radio-group v-model="configForm.configType">
            <el-radio label="Y">是</el-radio>
            <el-radio label="N">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="configForm.remark"
            type="textarea"
            placeholder="请输入内容"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getConfigList,
  getConfig,
  addConfig,
  updateConfig,
  delConfig,
  exportConfig,
  refreshCache,
} from '@/api/system/config'
import { parseTime } from '@/utils/global'
import DictTag from '@/components/DictTag/index.vue'
import Pagination from '@/components/Pagination/index.vue'

// 遮罩层
const loading = ref(true)
// 选中数组
const ids = ref<number[]>([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 总条数
const total = ref(0)
// 参数配置表格数据
const configList = ref<any[]>([])
// 弹出层标题
const dialogTitle = ref('')
// 是否显示弹出层
const dialogVisible = ref(false)
// 日期范围
const dateRange = ref<string[]>([])

// 表单引用
const queryFormRef = ref<FormInstance>()
const configFormRef = ref<FormInstance>()

// 是否数据字典
const yesNoOptions = ref([
  { label: '是', value: 'Y', elTagType: 'success' },
  { label: '否', value: 'N', elTagType: 'info' },
])

// 查询参数
const queryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  configName: '',
  configKey: '',
  configType: '',
  beginTime: undefined,
  endTime: undefined,
})

// 参数配置表单数据
const configForm = reactive({
  configId: undefined,
  configName: '',
  configKey: '',
  configValue: '',
  configType: 'N',
  remark: '',
})

// 表单校验
const configFormRules: FormRules = {
  configName: [
    { required: true, message: '参数名称不能为空', trigger: 'blur' },
  ],
  configKey: [
    { required: true, message: '参数键名不能为空', trigger: 'blur' },
  ],
  configValue: [
    { required: true, message: '参数键值不能为空', trigger: 'blur' },
  ],
}

/** 查询参数配置列表 */
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryForm,
      beginTime: dateRange.value ? dateRange.value[0] : undefined,
      endTime: dateRange.value ? dateRange.value[1] : undefined,
    }
    const { data } = await getConfigList(params)
    configList.value = data.rows
    total.value = data.total
  } catch (error) {
    console.error('获取参数配置列表失败:', error)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryForm.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = []
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.configId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset()
  dialogVisible.value = true
  dialogTitle.value = '添加参数配置'
}

/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset()
  const configId = row?.configId || ids.value[0]
  
  try {
    const { data } = await getConfig(configId)
    Object.assign(configForm, data)
    dialogVisible.value = true
    dialogTitle.value = '修改参数配置'
  } catch (error) {
    console.error('获取参数配置信息失败:', error)
  }
}

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  const configIds = row?.configId ? [row.configId] : ids.value
  
  try {
    await ElMessageBox.confirm(
      `是否确认删除参数编号为"${configIds}"的数据项？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await delConfig(configIds)
    await getList()
    ElMessage.success('删除成功')
  } catch (error) {
    console.log('取消删除')
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await ElMessageBox.confirm('是否确认导出所有参数配置数据项？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    const params = {
      ...queryForm,
      beginTime: dateRange.value ? dateRange.value[0] : undefined,
      endTime: dateRange.value ? dateRange.value[1] : undefined,
    }
    
    await exportConfig(params)
  } catch (error) {
    console.log('取消导出')
  }
}

/** 刷新缓存按钮操作 */
const handleRefreshCache = async () => {
  try {
    await ElMessageBox.confirm('是否确认刷新参数缓存？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    await refreshCache()
  } catch (error) {
    console.log('取消刷新缓存')
  }
}

/** 提交按钮 */
const submitForm = () => {
  configFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (configForm.configId !== undefined) {
          await updateConfig(configForm)
        } else {
          await addConfig(configForm)
        }
        dialogVisible.value = false
        await getList()
      } catch (error) {
        console.error('提交参数配置失败:', error)
      }
    }
  })
}

/** 取消按钮 */
const cancel = () => {
  dialogVisible.value = false
  reset()
}

/** 表单重置 */
const reset = () => {
  Object.assign(configForm, {
    configId: undefined,
    configName: '',
    configKey: '',
    configValue: '',
    configType: 'N',
    remark: '',
  })
  configFormRef.value?.resetFields()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.config-management {
  padding: 20px;
}

.search-card,
.operation-card {
  margin-bottom: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.left-operations {
  display: flex;
  gap: 8px;
}

.right-operations {
  display: flex;
  gap: 8px;
}

:deep(.el-table) {
  .el-table__cell {
    padding: 8px 0;
  }
}

.dialog-footer {
  text-align: center;
}
</style>

